package ru.ipo.problemsapi;

import ru.ipo.dces.utils.FileSystemUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: ilya
 * Date: 14.04.11
 * Time: 12:43
 */
public class PlainFolderProblem implements Problem {

    private File folder;

    public PlainFolderProblem(String path) {
        this(new File(path));
    }

    public PlainFolderProblem(File folder) {
        this.folder = folder.getAbsoluteFile();
    }

    public InputStream getReadStream(String name) {
        try {
            return new FileInputStream(folder.getPath() + "/" + name);
        } catch (FileNotFoundException e) {
            return null;
        }
    }

    public String getString(String name) {
        try {
            FileInputStream fr = new FileInputStream(folder.getPath() + "/" + name);
            return FileSystemUtils.inputStreamToString(fr, new ExtendedProblem(this).getEncoding(name));

        } catch (FileNotFoundException e) {
            return null;
        }
    }

    public boolean isTeacher(String name) {
        return false;
    }

    private List<String> getDirFiles(File folder, String base) {
        List<String> result = new ArrayList<String>();

        for (File file : folder.listFiles())
            if (file.isDirectory())
                result.addAll(getDirFiles(file, base + file.getName() + "/"));
            else
                result.add(base + file.getName());

        return result;
    }

    public List<String> listNames() {
        return getDirFiles(folder, "");
    }
}
